package Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.DAOFactory;
import DAO.PackageDAO;
import javabean.Package;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/addPackage")
public class addPackageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String packageName = request.getParameter("PackageName");
        int callTime = Integer.parseInt(request.getParameter("CallTime"));
        int mobileData = Integer.parseInt(request.getParameter("MobileDate"));
        String packageDescription = request.getParameter("PackageDescription");
        int validityPeriod = Integer.parseInt(request.getParameter("ValidityPeriod"));
        double price = Double.parseDouble(request.getParameter("Price"));
        
        PackageDAO packageDAO = (PackageDAO) DAOFactory.getPackageDAOInstance();
        Package newPackage = new Package();
        newPackage.setPackageName(packageName);
        newPackage.setCallTime(callTime);
        newPackage.setMobileDate(mobileData);
        newPackage.setPackageDescription(packageDescription);
        newPackage.setValidityPeriod(validityPeriod);
        newPackage.setPrice(price);
        PrintWriter out = response.getWriter();
        response.setContentType("text/html; charset=UTF-8");
        try {
            if (packageDAO.addPackage(newPackage)) {
                request.setAttribute("message", "success");
                out.print("<script>alert('套餐添加成功!');window.location.href='PackageManager'</script>");
            } else {
                request.setAttribute("message", "fail");
                out.print("<script>alert('套餐添加失败!');window.location.href='PackageManager'</script>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
